<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>local storage</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="wrapper">
        <h2>local tapas</h2>
        <p></p>
        <ul class="plates">
            <li>loading......</li>
        </ul>
        <form class="add-item">
            <input type="text" placeholder="item1 name" required name="item">
            <input type="submit">
        </form>
    </div>
<script>
    const additem = document.querySelector('.add-item');
    const itemlist = document.querySelector('.plates');
    // 从 localStorage 读取数据，如果没有则使用默认数据
    let items = JSON.parse(localStorage.getItem('todos')) || [{
        text: '给我的文章点赞',
        done: false
    }];

    // 函数式封装
    function populateList(plates = [], platesList) {
        platesList.innerHTML = plates.map((plate, i) => {
            return `
                <li>
                    <input type="checkbox" data-index=${i} id="item${i}"
                    ${plate.done ? 'checked' : ''}
                    />
                    <label for="item${i}">${plate.text}</label> <!-- 修正：lable -> label -->
                </li>
                `;
        }).join(''); // map返回数组，需要转换为字符串
    }
    // 初始化列表
    populateList(items, itemlist);
    // 添加项目的函数 - 重命名避免冲突
    function handleSubmit(event) {
        event.preventDefault(); // 阻止默认行为
        
        const text = (this.querySelector('[name=item]')).value.trim(); // 去除空格
        if (!text) return; // 如果文本为空则不添加
        
        const newItem = {
            text: text,
            done: false
        };
        items.push(newItem);
        
        // 持久化存储 - 修正：需要两个参数
        localStorage.setItem('todos', JSON.stringify(items));
        
        populateList(items, itemlist);
        this.reset();
    }

    // 添加事件监听器 - 修正：使用正确的变量名
    additem.addEventListener('submit', handleSubmit);
    function toggleDone(event){
        const el  =event.target;
        console.log(el);
        const index=el.dataset.index;
        items[index].done=!items[index].done;
        localStorage.setItem('todos',JSON.stringify(items));
        populateList(items,itemlist);
    }
    itemlist.addEventListener('click',toggleDone);
</script>
</body>
</html>